package com.lagou.handler;

import com.lagou.request.RpcRequest;
import com.lagou.util.AppUtil;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import org.springframework.stereotype.Component;

import java.lang.reflect.Method;

@Component
public class MyHandler extends ChannelInboundHandlerAdapter {


    /**
     * 当客户端读取数据时，该方法会被调用
     * @param ctx
     * @param msg
     * @throws Exception
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        try{
            RpcRequest rpcRequest = (RpcRequest) msg;
            Class<?> clazz = Class.forName(rpcRequest.getClassName());

            Object bean = AppUtil.getObject(clazz);
            Method method = clazz.getDeclaredMethod(rpcRequest.getMethodName(), rpcRequest.getParameterTypes());
            Object obj = method.invoke(bean, rpcRequest.getParameters());

            ctx.writeAndFlush(obj.toString());
        }catch (Exception e){
            ctx.writeAndFlush("");
        }

    }
}
